import { createVNode as _createVNode, mergeProps as _mergeProps } from "vue";
import { extend, isObject, inBrowser } from "../utils/index.mjs";
import { mountComponent, usePopupState } from "../utils/mount-component.mjs";
import VanNotify from "./Notify.mjs";
let timer;
let instance; // 全局公用一个vanNotify
const parseOptions = (message) => isObject(message) ? message : {
  message
};

// 生成vanNotify包装实例
function initInstance() {
  // mountComponent手动挂载vanNotify组件到body下面并返回实例
  // 功能嵌套vanNotify组件, 通过usePopupState插入开关量, 并且通过open能动态改变state的值
  ({
    instance
  } = mountComponent({
    setup() {
      const {
        state,
        toggle
      } = usePopupState();
      return () => _createVNode(VanNotify, _mergeProps(state, {
        "onUpdate:show": toggle
      }), null);
    }
  }));
}

// 默认配置
const getDefaultOptions = () => ({
  type: "danger",
  color: void 0,
  message: "",
  onClose: void 0,
  onClick: void 0,
  onOpened: void 0,
  duration: 3e3,
  position: void 0,
  className: "",
  lockScroll: false,
  background: void 0
});
// 当前全局设定配置
let currentOptions = getDefaultOptions();
const closeNotify = () => {
  if (instance) {
    instance.toggle(false);
  }
};

// 函数式使用 vanNotify组件,options为string为展示文字, object为各项配置
function showNotify(options) {
  if (!inBrowser) {
    return;
  }
  // 第一次使用初始化
  if (!instance) {
    initInstance();
  }
  options = extend({}, currentOptions, parseOptions(options));
  instance.open(options);
  // 定义自动关闭
  clearTimeout(timer);
  if (options.duration > 0) {
    timer = setTimeout(closeNotify, options.duration);
  }
  return instance;
}
// 设置默认值
const setNotifyDefaultOptions = (options) => extend(currentOptions, options);
// 初始化默认值
const resetNotifyDefaultOptions = () => {
  currentOptions = getDefaultOptions();
};
export {
  closeNotify,
  resetNotifyDefaultOptions,
  setNotifyDefaultOptions,
  showNotify
};
